package com.example.user.myfirstapp.sqlitedb;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

/**
 * Created by user on 2016/5/23.
 */
public class DbHelper {
    private SqliteDb sqliteDb;
    private SQLiteDatabase sqliteDatabase;

    public DbHelper(Context context){
        sqliteDb=new SqliteDb(context);
    }

    public DbHelper(Context context,String dbname,SQLiteDatabase.CursorFactory factory,int version){
        sqliteDb=new SqliteDb(context,dbname,factory,version);
        sqliteDatabase = sqliteDb.getReadableDatabase();
    }

    public void close(){
        if(sqliteDatabase.isOpen()) sqliteDatabase.close();
        if(sqliteDb != null) sqliteDb.close();
    }

    /*
     * 插入数据
     * @param tablename     表名
     * @param values        要插入的数据
     * @return  result      返回新添记录的行号，与主键id无关
    */
    public long Insert(String tablename,ContentValues values){
        long result = 0;
        sqliteDatabase=sqliteDb.getWritableDatabase();
        if(sqliteDatabase.isOpen()){
            result = sqliteDatabase.insert(tablename, null, values);
        }
        close();//插入完成后释放资源
        return result;
    }

    public void clearTable(String tablename){
        String sql = "DELETE FROM " + tablename +";";
        sqliteDatabase=sqliteDb.getWritableDatabase();
        sqliteDatabase.execSQL(sql);
        close();//插入完成后释放资源
    }
}
